package com.hm.oauth.web;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.hm.common.common.CommonUtil;
import com.hm.common.common.EncryptUtil.Md5;
import com.hm.common.util.CommonDef;
import com.hm.oauth.auto.OauthProperties;
import com.hm.oauth.def.OauthDef;

/**
 * @author shishun.wang
 * @date 下午8:51:57 2016年8月29日
 * @version 1.0
 * @describe
 */
@Controller
public class EntranceController {

	@Autowired
	private OauthProperties oauthProperties;

	@Value("${application.message:Hello World}")
	private String message = "Hello World";

	@RequestMapping(value = { "", "/", "/index" })
	public String index(Model model, HttpServletRequest request) {
		model.addAttribute("message", this.message);
		if (CommonUtil.isNotEmpty(request.getParameter("error"))) {
			model.addAttribute("error", "用户名/密码错误");
		} else if (CommonUtil.isNotEmpty(request.getParameter("sessionError"))) {
			model.addAttribute("error", "会话超时,请重新登陆");
		}
		return "index";
	}

	@RequestMapping(value = "main")
	public String main(Model model) {
		model.addAttribute("message", this.message);
		return "main";
	}

	@RequestMapping("/404")
	public String error_404() {
		return "error/404";
	}

	@RequestMapping("login")
	public String login(HttpServletRequest request, Model model) {
		String username = request.getParameter(OauthDef.LOGIN_USERNAME) + "";
		String password = Md5.getMD5Code(request.getParameter(OauthDef.LOGIN_PASSWORD) + "");
		if (oauthProperties.getRootUser().getPassword().equals(password)
				&& oauthProperties.getRootUser().getUsername().equals(Md5.getMD5Code(username))) {
			request.getSession().setAttribute(CommonDef.BaseInit.SessionOrCookieToken.SESSION_LOGIN_USER_INFO,
					username);
			model.addAttribute("username", username);
			return "redirect:/main?code=" + CommonUtil.generationToken();
		}
		return "redirect:/index?error=true&code=" + CommonUtil.generationToken();
	}
}
